package com.example.cs4.controller;

import com.example.cs4.model.ChatHistory;
import com.example.cs4.service.ChatHistoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.List;

@RestController
@RequestMapping("/api/chat-history")
@Api(tags = "聊天历史记录服务")
public class ChatHistoryController extends TextWebSocketHandler {

    @Autowired
    private ChatHistoryService chatHistoryService;

    /**
     * 保存聊天历史记录
     * @param chatHistory 聊天历史记录对象
     * @return 成功响应
     */
    @PostMapping
    @ApiOperation(value = "保存聊天历史记录", notes = "保存聊天历史记录")
    public ResponseEntity<Void> saveChatHistory(@RequestBody ChatHistory chatHistory) {
        chatHistoryService.saveChatHistory(chatHistory);
        return ResponseEntity.ok().build();
    }

    /**
     * 获取所有公共历史消息
     * @return 聊天历史记录列表
     */
    @GetMapping("/all")
    @ApiOperation(value = "获取所有公共历史消息", notes = "获取所有公共历史消息")
    public ResponseEntity<List<ChatHistory>> getAllChatHistory() {
        List<ChatHistory> chatHistories = chatHistoryService.getAllChatHistory();
        return ResponseEntity.ok(chatHistories);
    }

    /**
     * 根据用户查询聊天历史记录
     * @param user 用户名
     * @return 聊天历史记录列表
     */
    @GetMapping("/user/{user}")
    @ApiOperation(value = "根据用户聊天查询历史记录" ,notes = "根据用户查询聊天历史记录")
    public ResponseEntity<List<ChatHistory>> getChatHistoryByUser(@PathVariable String user) {
        List<ChatHistory> chatHistories = chatHistoryService.getChatHistoryForUser(user);
        return ResponseEntity.ok(chatHistories);
    }

    /**
     * 根据接收者或发送者查询聊天历史记录
     * @param receiver 接收者用户名
     * @param sender 发送者用户名
     * @return 聊天历史记录列表
     */
    @GetMapping("/receiver-or-sender")
    @ApiOperation(value = "根据接收者或发送者查询聊天历史记录", notes = "根据接收者或发送者查询聊天历史记录")
    public ResponseEntity<List<ChatHistory>> getChatHistoryByReceiverOrSender(@RequestParam String receiver, @RequestParam String sender) {
        List<ChatHistory> chatHistories = chatHistoryService.getChatHistoryByReceiverOrSender(receiver, sender);
        return ResponseEntity.ok(chatHistories);
    }
}
